<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @close="closeDialog" @open="openDialog">
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="checkList">
      <!-- 注意：label决定当前选中的值 -->
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="confirm">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { assignRoles } from '@/api/employee'
import { getUserDetailById } from '@/api/user'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    curId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      checkList: [],
      roleList: []
    }
  },
  methods: {
    //   关闭弹窗
    closeDialog() {
      this.$emit('close-dialog')
    },
    // 打开弹窗
    openDialog() {
      // 思考 ： 怎么在获取到角色列表之后 再让 请求详情  使用 promise
      this.hGetRoleList().then(() => {
        this.hGetDetail()
      })
    },
    // 获取角色列表
    hGetRoleList() {
      return new Promise((resolve, reject) => {
        getRoleList({ page: 1, pagesize: 100 }).then((res) => {
          this.roleList = res.rows
          resolve()
        })
      })
    },
    // 获取员工详情
    async hGetDetail() {
      const res = await getUserDetailById(this.curId)
      this.checkList = res.roleIds
    },
    // 提交
    async confirm() {
      await assignRoles({ id: this.curId, roleIds: this.checkList })
      this.closeDialog()
    }
  }
}
</script>
<style lang='scss' scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      width: 120px;
    }
  }
}
</style>
